package org.dreamwork.jasmine2.restful.client.gui.model;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.dreamwork.gson.GsonHelper;
import org.dreamwork.jasmine2.restful.APIDefinition;
import org.dreamwork.jasmine2.restful.MethodDefinition;
import org.dreamwork.jasmine2.restful.client.gui.util.KeyUtil;

import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeNode;
import java.util.Map;

/**
 * Created by IntelliJ IDEA.
 * User: seth.yang
 * Date: 2014/12/8
 * Time: 19:58
 */
public class APITreeModel extends DefaultTreeModel {
    private Map<String, APIDefinition> defs;

    public APITreeModel () {
        super (new DefaultMutableTreeNode ("API"));
    }

    public APITreeModel (TreeNode root) {
        super (root);
    }

    public APITreeModel (TreeNode root, boolean asksAllowsChildren) {
        super (root, asksAllowsChildren);
    }

    @SuppressWarnings ("unchecked")
    public void setMap (Map<String, Object> map) {
        final RootTreeNode root = new RootTreeNode (map);
        map = (Map<String, Object>) map.get ("api-mapping");

        Gson g = GsonHelper.getGson (true);
        String temp = g.toJson (map);
        defs = g.fromJson (temp, new TypeToken<Map<String, APIDefinition>> () {}.getType ());
        for (APIDefinition api : defs.values ()) {
            ApiTreeNode apiNode = new ApiTreeNode (api);
            root.insert (apiNode, root.getChildCount ());

            Map<String, MethodDefinition> methods = api.getMethods ();
            for (MethodDefinition md : methods.values ()) {
                apiNode.insert (new MethodTreeNode (md), apiNode.getChildCount ());
            }
        }

        KeyUtil.setContext (root.getSecureContext ());

        SwingUtilities.invokeLater (new Runnable () {
            @Override
            public void run () {
                setRoot (root);
            }
        });
    }

    public Map<String, APIDefinition> getDefs () {
        return defs;
    }
}